#!/bin/bash

set -e

function get_module() {
  local path=$1;
  while true; do
    path=$(dirname $path);
    if [ -f "$path/pom.xml" ]; then
      echo "$path";
      return;
    elif [[ "./" =~ "$path" ]]; then
      return;
    fi
  done
}

cd java;

modules=();

for file in $(git diff --relative --name-only --cached \*.java); do
  module=$(get_module "$file");
  if [ "" != "$module" ] \
      && [[ ! " ${modules[@]} " =~ " $module " ]]; then
    modules+=("$module");
  fi
done;

if [ ${#modules[@]} -eq 0 ]; then
  exit;
fi

modules_arg=$(printf ",%s" "${modules[@]}");
modules_arg=${modules_arg:1};

export MAVEN_OPTS="-client
  -XX:+TieredCompilation
  -XX:TieredStopAtLevel=1
  -Xverify:none";

mvn -q -pl "$modules_arg" checkstyle:check;

cd -;
